<template>
  <div class="device-table">
    <div class="header">
      <h2>设备列表</h2>
      <el-button type="primary" :icon="Refresh" @click="refreshDeviceList" :loading="loading">
        刷新
      </el-button>
    </div>
    
    <el-table
      :data="deviceList"
      style="width: 100%"
      border
      stripe
      v-loading="loading"
    >
      <el-table-column
        prop="name"
        label="设备名称"
        width="120"
      />
      <el-table-column
        prop="type"
        label="设备类型"
        width="120"
      />
      <el-table-column
        prop="description"
        label="设备描述"
        width="180"
      />
      <el-table-column
        prop="equipmentTime"
        label="设备时间"
        width="160"
      />
      <el-table-column
        prop="updatedAt"
        label="更新时间"
        width="180"
      >
        <template #default="scope">
          {{ new Date(scope.row.updatedAt).toLocaleString() }}
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="200"
        fixed="right"
      >
        <template #default="scope">
          <el-button-group>
            <el-button 
              type="primary" 
              size="small"
              @click="handleDeviceDetail(scope.row)"
            >
              详情
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      v-model="detailDialogVisible"
      title="设备详情"
      width="600px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="设备名称">{{ currentDevice.name }}</el-descriptions-item>
        <el-descriptions-item label="设备ID">{{ currentDevice.id }}</el-descriptions-item>
        <el-descriptions-item label="设备类型">{{ currentDevice.type }}</el-descriptions-item>
        <el-descriptions-item label="设备时间">{{ currentDevice.equipmentTime }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ new Date(currentDevice.createdAt).toLocaleString() }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ new Date(currentDevice.updatedAt).toLocaleString() }}</el-descriptions-item>
        <el-descriptions-item label="设备描述" :span="2">{{ currentDevice.description }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

const deviceList = ref([])
const loading = ref(false)
const detailDialogVisible = ref(false)
const currentDevice = ref({})

// 获取设备列表
const fetchDeviceList = async () => {
  loading.value = true
  try {
    const token = localStorage.getItem('token')
    // 获取用户信息和权限
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    const userRole = localStorage.getItem('userRole') || ''
    

    const response = await fetch('https://penglink.pcwxcn.top/api/equipment/latest', {
      headers: {
        'Authorization': `Bearer ${token}`,
        'Accept': 'application/json'
      }
    })

    if (!response.ok) {
      throw new Error('获取设备列表失败')
    }

    const result = await response.json()
    if (result.code === 200) {
      // 根据用户角色过滤设备列表
      let filteredDevices = result.data;
      
      // 获取用户可访问的设备列表
      let userDevices = [];
      
      // 确保userDevices是数组
      if (userInfo.devices) {
        if (Array.isArray(userInfo.devices)) {
          userDevices = userInfo.devices;
        } else if (typeof userInfo.devices === 'string') {
          // 尝试解析字符串形式的devices
          try {
            userDevices = JSON.parse(userInfo.devices);
            if (!Array.isArray(userDevices)) {
              userDevices = [userDevices]; // 如果解析后不是数组，则转为数组
            }
          } catch (e) {
            // 如果解析失败，尝试将其作为单个设备ID处理
            userDevices = [userInfo.devices];
            console.error('解析devices字符串失败:', e);
          }
        } else {
          // 如果是其他类型，尝试转换为数组
          userDevices = [userInfo.devices];
        }
      }
      
      // 根据角色级别过滤设备
      // LV1(超级管理员)和LV2(管理员)可以查看所有设备
      // LV3(租户管理员)和LV4(设备用户)只能查看指定设备
      if (userRole === 'LV3' || userRole === 'LV4') {
        // 确保类型匹配，将两边都转为字符串进行比较
        filteredDevices = result.data.filter(device => {
          const deviceId = String(device.id);
          const hasAccess = userDevices.some(userDeviceId => {
            const userDevId = String(userDeviceId);
            return userDevId === deviceId;
          });
          return hasAccess;
        });
        
      } else {
      }
      
      deviceList.value = filteredDevices.map(item => ({
        id: item.id,
        name: item.equipment_name,
        type: item.equipment_type,
        auth: item.auth,
        description: item.equipment_description,
        equipmentTime: item.equipment_time,
        createdAt: item.created_at,
        updatedAt: item.updated_at
      })).sort((a, b) => {
        const numA = parseInt(a.name.match(/\d+/)?.[0] || '0')
        const numB = parseInt(b.name.match(/\d+/)?.[0] || '0')
        return numA - numB
      })
    } else {
      throw new Error(result.message || '获取设备列表失败')
    }
  } catch (error) {
    console.error('获取设备列表失败:', error)
    ElMessage.error(error.message)
  } finally {
    loading.value = false
  }
}

// 刷新设备列表
const refreshDeviceList = () => {
  fetchDeviceList()
}

// 查看设备详情
const handleDeviceDetail = (device) => {
  currentDevice.value = { ...device };
  detailDialogVisible.value = true;
};

onMounted(() => {
  fetchDeviceList()
})
</script>

<style scoped>
.device-table {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  font-size: 20px;
  color: #303133;
}

:deep(.el-dialog__body) {
  padding: 20px;
}
</style>
